package com.ruoyi.system.service.impl;

import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.domain.SysKey;
import com.ruoyi.system.mapper.SysUserKeyMapper;
import com.ruoyi.system.service.SysUserKeyService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;

@Service
public class SysUserKeyServiceImpl implements SysUserKeyService {
    @Resource
    private SysUserKeyMapper sysUserKeyMapper;

    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public ArrayList<SysKey> selectSysKeyList() {
        return sysUserKeyMapper.selectSysKeyList(null);
    }

    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public AjaxResult addKey(SysKey sysKey) {
        if (sysKey.getNumber() <= 0) {
            return AjaxResult.error("数量不能低于1张");
        }
        if (sysKey.getNumber() > 500) {
            return AjaxResult.error("单次数量不能大于500张");
        }
        StringBuilder stringBuffer = new StringBuilder();
        for (int i = 0; i < sysKey.getNumber(); i++) {
            sysKey.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
            sysKey.setIsActivated("0");
            sysKey.setAccount("未使用");
            sysKey.setPersonName(SecurityUtils.getUsername());
            sysKey.setStatus("0");
            String key = UUID.randomUUID().toString().replace("-", "");
            switch (sysKey.getKeyTypes()) {
                case "0":
                    sysKey.setKeyNumber("TK" + key);
                    break;
                case "1":
                    sysKey.setKeyNumber("ZK" + key);
                    break;
                case "2":
                    sysKey.setKeyNumber("YK" + key);
                    break;
                case "3":
                    sysKey.setKeyNumber("CS" + key);
                    break;
            }
            stringBuffer.append(sysKey.getKeyNumber()).append("\n");
            sysUserKeyMapper.insertSysKey(sysKey);
        }
        return AjaxResult.success("新增成功", stringBuffer.toString());
    }

    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public AjaxResult delKey(SysKey sysKey) {
        sysUserKeyMapper.deleteSysKeyById(sysKey.getId());
        return AjaxResult.success("删除成功");
    }

    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public AjaxResult shutDown(String key) {
        // 查询当前卡密状态
        SysKey sysKey = sysUserKeyMapper.selectSysKey(key);
        sysKey.setStatus(sysKey.getStatus().equals("1") ? "0" : "1");
        sysUserKeyMapper.shutDown(sysKey);
        return AjaxResult.success(sysKey.getStatus().equals("1") ? "封停成功" : "解封成功");
    }


}
